import java.io.*;
import java.net.*;
import java.util.*;
import java.util.regex.*;

public class Visit {
	private String URL;
	private String pattern;
	private List<String> pageContent;
	
	public Visit(String URL) {
		this.URL = URL;
		this.pageContent = new ArrayList<String>();
		
		download();
	}
	
	public int numMatches(Pattern patt) {
		int numMatches = 0;
		
		for (String line : this.pageContent) {
			Matcher m = patt.matcher(line);
			
			while (m.find()) {
				numMatches++;
			}
		}
		
		return numMatches;
	}
	
	private void download() {
		try {
			URL url = new URL(this.URL);
			InputStream is = url.openConnection().getInputStream();
			BufferedReader rdr = new BufferedReader(new InputStreamReader(is));
			String line;
			
			while ((line = rdr.readLine()) != null) {
				this.pageContent.add(line);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		if (args.length != 2) {
			System.err.println("Usage:  Visit <url> <pattern>");
			System.exit(1);
		}
		
		String URL = args[0];
		String pattern = args[1];
		
		Visit visit = new Visit(URL);
		int numMatches = visit.numMatches(Pattern.compile(pattern));
		
		System.out.println("Found " + numMatches + " occurrences");
	}
}
